/**
 * 
 */
package weibo4j.crawler;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import weibo4j.Comment;
import weibo4j.Weibo;
import weibo4j.database.DataBaseUtil;

/**
 * @author longrui
 * 
 */
public class CommentCrawler extends CrawlerBase {
	private QueueBase queue4Status;
	private Connection commConn;
	private List<Comment> comments;
	private CrawlerBase mainCrawler;

	/**
	 * @param weibo
	 */
	public CommentCrawler(Weibo weibo) {
		super(weibo);
		// TODO Auto-generated constructor stub
	}

	public void init(CrawlerBase mainCrawler, QueueBase queue4Status) {
		this.queue4Status = queue4Status;
		commConn = DataBaseUtil.getDefaultConnection();
		this.mainCrawler = mainCrawler;
	}
	
	public QueueBase getQueueBaseType(){
		return queue4Status;
	}

	public void run() {
		CommentQueueRecord rec = null;
		try {
			System.out.println("Comment crawler is starting ...");			
			
			while (true) {				
				((UserInfoCrawler)mainCrawler).prepare(this);
				
				System.out.println("working... Comment queue's size:"
						+ queue4Status.getLength());
				rec = (CommentQueueRecord) queue4Status.poll();
				comments = super.getCommentsByStatusId(rec.commentedStatusId);

				// save comments into database;
				System.out.println("comments count: " + comments.size());
				for (Comment comm : comments) {
					DataBaseUtil.executeStatement(commConn, comm.getCommentSQLString("utf-8"));
					//DataBaseUtil.insert(statusConn, "comments",	Comment.getFiledString(),
					//		Comment.getEmptyValueString(),comm.getRecord("utf-8"));
					//System.out.println("insert comments by comment thread: " + i++);
					queue4Status.add(new CommentQueueRecord(comm.getId(),myDateTimeFormat.format(new Date())));
				}
				adjustFreq();
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub

	}

}
